import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

// POST /api/client/chat/sessions/clear - 清空所有聊天会话
async function handlePost(request: NextRequest): Promise<{ success: boolean }> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 查找该用户的所有聊天会话ID
  const sessions = await prisma.chatSession.findMany({
    where: { userId: userId },
    select: { id: true },
  });

  const sessionIds = sessions.map(s => s.id);

  if (sessionIds.length === 0) {
    return { success: true };
  }

  // 4. 删除该用户的所有聊天会话和消息
  await prisma.$transaction(async (prisma) => {
    // 首先删除所有消息
    await prisma.chatMessage.deleteMany({
      where: {
        sessionId: { in: sessionIds },
      },
    });

    // 然后删除所有聊天会话
    await prisma.chatSession.deleteMany({
      where: {
        userId: userId,
      },
    });
  });

  return { success: true };
}

export const POST = withMiddleware(handlePost);
